/* eslint-disable react/require-default-props */

import React, { forwardRef, useMemo, useState } from "react";
import cn from "classnames";

import { EyeIcon, EyeStrokeIcon } from "./icons";
import cls from "./Input.module.scss";

export interface InputUIProps {
  value: string;
  onChange: (e: React.FormEvent<HTMLInputElement>) => void;
  onBlur?: (e: React.FormEvent<HTMLInputElement>) => void;
  onFocus?: (e: React.FormEvent<HTMLInputElement>) => void;
  disabled?: boolean;
  label?: string;
  placeholder?: string;
  name?: string;
  type?: React.InputHTMLAttributes<HTMLInputElement>["type"];
  errorText?: string;
  autoComplete?: string;
  maxLength?: number;
}

export const Input = forwardRef((props: InputUIProps, ref) => {
  const {
    value,
    onChange,
    maxLength = undefined,
    disabled = false,
    onFocus = undefined,
    onBlur = undefined,
    placeholder = undefined,
    name = undefined,
    autoComplete = undefined,
    label = "",
    errorText = "",
    type = "text",
  } = props;

  const isPassword = type === "password";
  const [isPassHidden, setPassHidden] = useState(isPassword);

  const inputType = useMemo(() => {
    if (isPassword) {
      return isPassHidden ? "password" : "text";
    }

    return type;
  }, [type, isPassword, isPassHidden]);

  return (
    <div className={cls.root}>
      {label && <span className={cls.label}>{label}</span>}
      <div className={cls.input_wrap}>
        <input
          // @ts-ignore
          ref={ref}
          className={cn(cls.input, { [cls.input_error]: !!errorText })}
          type={inputType}
          value={value}
          onChange={onChange}
          onBlur={onBlur}
          onFocus={onFocus}
          placeholder={placeholder}
          disabled={disabled}
          name={name}
          style={{ paddingRight: isPassword ? 32 : 10 }}
          autoComplete={autoComplete}
          maxLength={maxLength}
        />

        {isPassword && (
          <button
            className={cls.password_toggle}
            type="button"
            onClick={() => setPassHidden(!isPassHidden)}
            tabIndex={-1}
            disabled={disabled}
          >
            {isPassHidden ? <EyeStrokeIcon /> : <EyeIcon />}
          </button>
        )}
      </div>

      <span
        className={cn(cls.error_wrap, {
          [cls.error_wrap_active]: !!errorText,
        })}
      >
        {errorText && <span className={cls.error}>{errorText}</span>}
      </span>
    </div>
  );
});

Input.displayName = "Input";
